#!/bin/bash
echo "============================================"
echo "=             空明物联网服务平台            = "
echo "=   安装程序, 有问题欢迎反馈 QQ:914055386   ="
echo "=                apidata.cc               ="
echo "=========================================="

if [ `whoami` != "root" ];then
	echo "请使用ROOT用户运行程序！" 
    exit
fi

echo "> 开始安装服务程序中 ......"


# 参数为空的时候取MAC地址作为SN
if [ ! -n "$1" ]; then
   arg_token=`ifconfig eth0 | grep "ether" | awk '{print $2}' | awk -F: '{print $1 $2 $3 $4 $5 $6}'`
else 
   arg_token=$1
fi
echo $arg_token


app_path=/home/pi/kongming
sudo mkdir -p $app_path
cd $app_path

write_app_config(){
    echo "> 正在写入配置文件......"
    sudo cat>$app_path/app.json<<EOF
{
    "version":"1.0.0",
    "sn":"$arg_token",
    "rest_host":"111.229.24.16",
    "rest_port":9395,
    "service_host":"111.229.24.16",
    "service_port":8881
}
EOF
}


write_supervisord(){
    echo "> 写supervisor配置......"
    sudo cat>/etc/supervisor/conf.d/kongming.conf<<EOF
[program:kongming]
command = python $app_path/main.py
directory = $app_path
user = root
numprocs = 1
autostart = true
autorestart = true
EOF
}


down_sdk(){
    echo ">  下载SDK......"
    sudo apt-get install -y wget
    sudo wget http://apidata.cc/kongming-sdk.tar
    sudo tar -xf kongming-sdk.tar
}


sudo apt-get update
write_app_config
down_sdk

echo ">  安装必要组件......"
sudo apt-get install -y gcc
sudo apt-get install -y python-pip
sudo apt-get install -y python-dev

echo "> 安装python 模块......"
sudo pip install -r requirements.txt -i https://pypi.doubanio.com/simple


echo "> 安装supervisor......"
sudo apt-get install -y supervisor
write_supervisord

echo "> 启动supervisor......"


sudo touch /var/run/supervisor.sock 
sudo chmod 777 /var/run/supervisor.sock 

sudo service supervisor start



echo "> 开始启动......"
sudo supervisorctl update
sudo supervisorctl reload
sudo update-rc.d supervisor defaults
sudo supervisorctl status
sudo supervisorctl reload
sudo supervisorctl status
echo "========================================="
echo "欢迎使用！空明物联网平台服务 apidata.cc"
echo "如果设备上线失败！ 请输入reboot重启设备"
echo "设备SN:$arg_token"